package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import com.blankj.utilcode.util.LogUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.launch.IMConfigYMAL;
import com.blockmeta.bbs.businesslibrary.net.okhttp.OKHttpGetReq;
import com.blockmeta.bbs.businesslibrary.pojo.IMConfigPOJO;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.widget.LengthLimitEditText;
import com.blockmeta.bbs.immodule.widget.MyBottomPopupWindow;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author airthor
 * @date 2019/2/19
 * 创建圈子之基本资料
 */
public class CreateGroupInfoActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R2.id.iv_upload_avatar)
    CircleImageView mIvUploadAvatar;
    @BindView(R2.id.edt_circle_name)
    LengthLimitEditText mEdtCircleName;
    @BindView(R2.id.edt_circle_info)
    LengthLimitEditText mEdtCircleInfo;
    @BindView(R2.id.rg_circle_kind)
    Spinner mRgCircleKind;
    @BindView(R2.id.spinner_grade_limit)
    Spinner mSpinnerGradeLimit;
    public static final String[] GROUP_LEVELS = {"小白（无要求）","水手","船员","队长","副船长","船长","海盗王"};
    public List<String> GROUP_TYPES = new ArrayList<>();
    public HashMap<String,Integer> TYPE_IDS = new HashMap<>();

    private MyBottomPopupWindow popupWindow;
    private HashMap<String,String> params = new HashMap<>();

    public static CreateGroupInfoActivity Instance = null;
    protected static IMConfigPOJO imConfigPOJO = IMConfigYMAL.getIMConfig();
    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_creat_group_info, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        Instance = this;
        initParams();
        bindControls();
    }

    private void bindControls() {
        initSpinner();
        initCircleTypeGroup();
    }

    private void initCircleTypeGroup() {
        if(imConfigPOJO == null || imConfigPOJO.getCircleType() == null){
            return;
        }
        for (IMConfigPOJO.CircleType type : imConfigPOJO.getCircleType()) {
            GROUP_TYPES.add(type.getName());
            TYPE_IDS.put(type.getName(),type.getId());
        }
        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(this,R.layout.spinner_item, GROUP_TYPES);
        arrayAdapter.setDropDownViewResource(R.layout.spinner_drop_item);
        mRgCircleKind.setAdapter(arrayAdapter);
        mRgCircleKind.setDropDownVerticalOffset(DimentionsUtil.dp2px(this,44f));
        mRgCircleKind.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                params.put("type", String.valueOf(TYPE_IDS.get(GROUP_TYPES.get(position))));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 初始化创建圈子的参数
     */
    private void initParams() {
        params.put("type","1");
        params.put("user_level","0");
        params.put("userId", AccountHelper.getUid());
    }

    private void initSpinner() {

        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(this,R.layout.spinner_item, GROUP_LEVELS);
        arrayAdapter.setDropDownViewResource(R.layout.spinner_drop_item);
        mSpinnerGradeLimit.setAdapter(arrayAdapter);
        mSpinnerGradeLimit.setDropDownVerticalOffset(DimentionsUtil.dp2px(this,44f));
        mSpinnerGradeLimit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                params.put("user_level",position+"");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @OnClick({R2.id.fl_back, R2.id.fl_next, R2.id.iv_upload_avatar})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();

        } else if (i == R.id.fl_next) {//下一步
            toNextPage();

        } else if (i == R.id.iv_upload_avatar) {//选择头像
            showIconChoice();

        } else {
        }
    }

    private void toNextPage() {
        String name = mEdtCircleName.getText().toString();
        if (TextUtils.isEmpty(name)){
            ToastUtil.show("圈子名字不能为空");
            return;
        }
        String info = mEdtCircleInfo.getText().toString();
        if (TextUtils.isEmpty(info)){
            ToastUtil.show("圈子简介不能为空");
            return;
        }
        if(!params.containsKey("logo")){
            ToastUtil.show("圈子头像不能为空");
            return;
        }

        params.put("name",name);
        params.put("desc",info);

        Intent intent = new Intent(this,CreateGroupSelectMemberActivity.class);
        intent.putExtra("params",params);
        startActivity(intent);
    }

    private void showIconChoice() {
        popupWindow = new MyBottomPopupWindow(mContext);
        popupWindow.tx2.setText("相册");
        popupWindow.tx3.setText("拍照");
        popupWindow.tx2.setOnClickListener(this);
        popupWindow.tx3.setOnClickListener(this);
        popupWindow.tx4.setOnClickListener(this);

        popupWindow.showPopupWindow();

    }
    @Override
    public void onClick(View v) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        int i = v.getId();
        if (i == R.id.popup_tx_2) {//相册
            getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions());

        } else if (i == R.id.popup_tx_3) {//拍照
            getTakePhoto().onPickFromCaptureWithCrop(imageUri, getCropOptions());

        } else if (i == R.id.popup_tx_4) {//取消
            popupWindow.dismiss();

        } else {
        }
    }

    //裁剪
    private CropOptions getCropOptions() {
        int height = Integer.parseInt("150");
        int width = Integer.parseInt("150");
        //TokePhoto裁剪工具
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setOutputX(width).setOutputY(height);
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        TImage image = result.getImage();
        String compressPath = image.getOriginalPath();
        Bitmap bitmap = BitmapFactory.decodeFile(compressPath);
        mIvUploadAvatar.setImageBitmap(bitmap);
        postIconToNet(new File(compressPath), compressPath);
        popupWindow.dismiss();

    }

    private void postIconToNet(final File file, final String compressPath) {
        ProgressBarUtil.showProgress(mContext);
        long currentTimeMillis = System.currentTimeMillis();
        //文件名唯一
        final String picName = currentTimeMillis + AccountHelper.getUid() + ".png";

        OKHttpGetReq okHttpGetReq = new OKHttpGetReq(mContext, Params.UpdateImPic + picName);
        ProgressBarUtil.showProgress(mContext);
        okHttpGetReq.getDataWithUid(new Callback() {

            @Override
            public void onError(String resp) {
                ProgressBarUtil.dismissProgress(mContext);
            }

            @Override
            public void onResponse(String resp, int id) {
                ProgressBarUtil.dismissProgress(mContext);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(resp);
                    String token = jsonObject.getString("token");
                    postIconToQiniu(file,token,compressPath, picName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void postIconToQiniu(File file, String token,final String compressPath,String picName) {
        ProgressBarUtil.showProgress(mContext);
        OkHttpUtils.post()
                .url(Params.QiNiuAddress)
                .addParams("key", picName)
                .addParams("token", token)
                .addFile("file", picName, file)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ProgressBarUtil.dismissProgress(mContext);
                        ToastUtil.show("上传失败,请检查网络");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ProgressBarUtil.dismissProgress(mContext);
                        if (code == 200) {
                            try {
                                Bitmap bitmap = BitmapFactory.decodeFile(compressPath);
                                mIvUploadAvatar.setImageBitmap(bitmap);
                                LogUtils.d("sss", "onResponse: "+response);
                                JSONObject jsonObject = new JSONObject(response);
                                String imgUrl= (String) jsonObject.get("key");
                                params.put("logo",Params.QiNiuHost + imgUrl);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.show("图片上传失败");
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        Instance = null;
        super.onDestroy();
    }
}
